package com.bang.study.day08.leetcode;

import com.bang.study.day08.RBTree;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Scanner;

/**
 * @Auther: Bang
 * @Date: 2019/9/19 0019 11:28
 * @Description:
 */
public class TestRB {
    public static void main(String[] args) {
        String filename = "pride-and-prejudice.txt";
        ArrayList<String> words = new ArrayList<>();
        if(readFile(filename, words)) {
            System.out.println("Total words: " + words.size());
            RBTree<String, Integer> rbTree = new RBTree<>();
            for (String word : words){
                if(rbTree.contains(word))
                    rbTree.set(word, rbTree.get(word) + 1);
                else
                    rbTree.add(word, 1);
            }

            System.out.println("Total different words: " + rbTree.getSize());
            System.out.println("Frequency of PRIDE: " + rbTree.get("pride"));
            System.out.println("Frequency of PREJUDICE: " + rbTree.get("prejudice"));
        }
    }


    private static boolean  readFile(String filename, ArrayList<String> words){
        // 文件读取
        Scanner scanner;

        try {
            filename = "E:\\study\\java_foundation\\parent\\data-structure\\src\\" + filename;
            File file = new File(filename);
            if(file.exists()){
                FileInputStream fis = new FileInputStream(file);
                scanner = new Scanner(new BufferedInputStream(fis), "UTF-8");
                scanner.useLocale(Locale.ENGLISH);
            }else {
                return false;
            }
        }
        catch(IOException ioe){
            System.out.println("Cannot open " + filename);
            return false;
        }

        // 简单分词
        // 这个分词方式相对简陋, 没有考虑很多文本处理中的特殊问题
        // 在这里只做demo展示用
        if (scanner.hasNextLine()) {
            String contents = scanner.useDelimiter("\\A").next();
            int start = firstCharacterIndex(contents, 0);
            for (int i = start + 1; i <= contents.length(); ) {
                if (i == contents.length() || !Character.isLetter(contents.charAt(i))) {
                    String word = contents.substring(start, i).toLowerCase();
                    words.add(word);
                    start = firstCharacterIndex(contents, i);
                    i = start + 1;
                } else {
                    i++;
                }
            }
        }

        return true;
    }

    // 寻找字符串s中，从start的位置开始的第一个字母字符的位置
    private static int firstCharacterIndex(String s, int start){

        for( int i = start ; i < s.length() ; i ++ ) {
            if( Character.isLetter(s.charAt(i)) ) {
                return i;
            }
        }
        return s.length();
    }
}
